<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="shortcut icon" type="image/png" href="/stock/images/stock.png" />
 
<script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="js/jquery.jeditable.js" type="text/javascript"></script>
<script src="js/jquery.json-2.2.js" type="text/javascript"></script>
<script src="js/dbstock.js" type="text/javascript"></script>
<link type="text/css" rel="stylesheet" href="css/bluedream.css" />


<script>
if (typeof(localStorage) == "undefined" ) {
	alert("Your browser does not support HTML5 localStorage. Try upgrading.");
}
var sdata = Array();	
var thandler;
var db = new DbStock();
var interval = 60*1000;
var username = 'hjue';
$(document).ready(function() {

 $('<div id="loading">正在加载数据，请稍候....</div>').prependTo("div:first").css({"z-index":"1001",position:"fixed","font-size":"11pt","font-weight":"bold",top:"0px",left:"50%",width: "250px", height:"20px","background-color":"#FFFFAF","display":"none"});
    		     $("#loading").ajaxStart(function(){
    		            $(this).show();
    		      });

    		     $("#loading").ajaxStop(function(){
    		            $(this).hide();
    		      });

	refresh_data();
	start();
	$("#btnstop").click(function(){
		stop();
	});
	$("#btnstart").click(function(){
		start();
	});
	$("#btnclear").click(function(){
		newMessageRemind.clear();
	});	
		
	$("#btndel").click(function(){
		$("input[name='chkstock']").filter(':checked').each(function(){
			db.delete_symbol(this.value);
			refresh_data();
		});
	
	});
	
	$("#btnsave").click(function(){
		var r=confirm("Are you sure save "+username+" data to server,this will overwrite data.");
		if (r==true)
		{
			var strdb = db.load_db_datastring();
			$.post("save.php", { 'data': strdb,'action':'save','username':username},
					   function(data){
					alert('save succ!');
					   }, "json");					
		}else
			return ;
		

	});
	
	$("#btnload").click(function(){
		$.post("save.php", { 'action':'load','username':username},function(data){
			if(data.data!=null && data.data!="")
			{
				db.set_db_datastring(data.data);
				refresh_data();
			}
			
		}, "json");
	});	
	
	$("#btnadd").click(function(){
		var code = $("#addcode").val();
		if(code==null || code=="") return ;
		var arr_code = code.split(',');
		var i;
		for(i=0;i<arr_code.length;i++)
		{
			if(isNaN(arr_code[i]) || arr_code[i].length!=6)
			{
				
				continue;
			}
			
			db.add_symbol(arr_code[i]);
		}
		refresh_data();
	});
	
});	

function start()
{
	thandler = setInterval(refresh_data, interval);
}

function stop()
{
	clearTimeout(thandler);
}



function refresh_data()
{
	/*
  var params = argv.split(",");
	
	*/
	var q = window.location.search.substring(1);
	if(q!=null && q!="")
		username = q;
	
	var d = new Date();
	var ds = (d.getHours()+''+d.getMinutes());
	if((ds<'0915' || ds>'1500' || (ds>'1130' && ds<'1300')) && sdata.length>0) 
	{
		return false;
	}

	var squery = db.get_sina_query();
	if(squery==null || squery=="")
	{	
		squery = "sh000001,sz399001";
		db.add_symbol('sh000001');
		db.add_symbol('sz399001');
	};
	
	$.ajax({
		  url: 'http://hq.sinajs.cn/list='+squery,
		  type: "GET",
		  dataType: 'script',
		  beforeSend :function(xmlHttp){
		  	xmlHttp.setRequestHeader("If-Modified-Since","0");
            xmlHttp.setRequestHeader("Cache-Control","no-cache");
		  	},
		  cache:true,
		  success: function(){
			  sdata = Array();
			  var params = squery.split(",");
			  var symbol;
			  var i;
			  var arr_sinfo,row;
			  for(i=0;i<params.length;i++)
			  {
			  	//var sinfo = eval("hq_str_"+params[i]);
			  	var sinfo = window["hq_str_"+params[i]];
			  	//if(i==0) console.log(sinfo);
			  	if(sinfo!="")
			  	{
			  		arr_sinfo = sinfo.split(",")
			  		if(arr_sinfo.length!=32) continue;
			  		//0 name 
			  		//1 today open price
			  		//2 yestoday close price
			  		//3 current price
			  		//4 today max price
			  		//5 today min price
			  		//8 trade quantity
			  		//9 trade money
			  		//30 date
			  		//31 time
			  		//alert(arr_sinfo[3]);
			  		row = Array();
			  		var j = 0; 
			  		row[0] = arr_sinfo[0];
			  		j++;
			  		//j =1 
			  		row[j] = params[i];
			  		symbol = row[j]; 
			  		//j=2
					j++;	  	
			  		if(arr_sinfo[2]>0)
			  		{
			  			row[j] = Math.round((arr_sinfo[3] - arr_sinfo[2])*10000/arr_sinfo[2])/100;
			  		}else{
			  			row[j] = '-';
			  		}
			  		
			  		//最新 j =3
			  		j++;
			  		row[j] = arr_sinfo[3];
			  		
			  		
			  		//j=4
			  		j++;
			  		var cellval;
			  		var stock = db.get_symbol_info(symbol);
			  		
			  		
			  		cellval = stock['buy_price'];
			  		if(cellval==null || cellval=="")
			  			row[j] = '';
			  		else
			  			row[j] = cellval;
			  		
			  		//j=5
			  		j++;
			  		cellval = stock['alarm_max_price'];
			  		if(cellval==null)
			  			row[j] = '';
			  		else
			  			row[j] = cellval;
			  		//j=6
			  		j++;
			  		cellval = stock['alarm_min_price'];
			  		if(cellval==null)
			  			row[j] = '';
			  		else
			  			row[j] = cellval;
			  		//
			  		
			  		//涨跌额 j =7 
			  		j++;
			  		row[j] = Math.round(100*(arr_sinfo[3] - arr_sinfo[2]))/100;
			  		
			  		//成交量 j = 8
			  		j++;
			  		row[j] = Math.round(arr_sinfo[8]/100);
			  		
			  		//成交额 j = 9
			  		j++;
			  		row[j] = Math.round(arr_sinfo[9]/10000);
			  		
			  		//昨收/今开盘 j =10
			  		j++;
			  		row[j] = arr_sinfo[2]+'/'+arr_sinfo[1];
			  		
			  		//最高/最低价 j = 11
			  		j++;
			  		row[j] = arr_sinfo[4]+'/'+arr_sinfo[5];
			  		sdata.push(row);
			  	}
			  		
			  } //end for
			  
			  makegrid();
		  	}
		});	
	
	//window.focus();
}

function makegrid()
{
	var table = '<table><thead>';
	table += '<th>&nbsp;</th>';	
	table += '<th>名称</th>';
	table += '<th>代码</th>';
	table += '<th>涨跌幅</th>';
	table += '<th>最新价</th>';
	table += '<th>买入价</th>';
	table += '<th>提醒上限价</th>';
	table += '<th>提醒下限价</th>';	
	table += '<th>涨跌额</th>';
	table += '<th>成交量(手)</th>';
	table += '<th>成交额(万)</th>';
	//table += '<th>换手率</th>';
	//table += '<th>买入/卖出价</th>';
	table += '<th>昨收/今开盘</th>';
	table += '<th>最高/最低价</th>';
	

	table += '</thead>';
	var message = '';
	var alarm_row = false;
	for(i=0;i<sdata.length;i++)
	{
		alarm_row = false; 
		if(sdata[i][5]!='' && parseFloat(sdata[i][3]) > parseFloat(sdata[i][5]))
		{
			alarm_row = true; 
			message += sdata[i][0] +'('+ sdata[i][1] +')' + '超过设定值'+"<br/>";
		}
		
		if(sdata[i][6]!='' && parseFloat(sdata[i][3]) < parseFloat(sdata[i][6]))
		{
			alarm_row = true;
			message += sdata[i][0]+'('+ sdata[i][1] +')'+ '低于设定值'+"<br/>";
		}			
		table += '<tr';
		if(alarm_row) 
		{
			table += ' style="background:#FFFFAF" ';
			
		}
		table += '>';
	
		table += '<td><input name="chkstock" type="checkbox" value="'+sdata[i][1]+'"/></td>';
		for(j=0;j<sdata[i].length;j++)
		{
			table += '<td ';

			if(j==2)
			{
				if(parseFloat(sdata[i][j])>=0)
				{
					table += ' style="color:red" ';				
				}else
				{
					table += ' style="color:green" ';
				}
				
			}
			if(j==4 || j==5 || j==6) table += ' ref="'+i+'-'+j+'" class="editable" ';
			table += '>';
			

			if(j==0)
			{
				table += '<a href="'+'http://finance.sina.com.cn/realstock/company/'+ sdata[i][1]+'/nc.shtml'+'" target="_blank">'+sdata[i][j]+'</a>';
				
			}else{
			
				table += sdata[i][j];
			}

			if(j==2)
			{
				if(!isNaN(parseInt(sdata[i][j],10)))
				{
					table += '% ';				
				}
			}
			
			table += '</td>';
		}
		

		table += '</tr>';
	}
	
	
  table += '</table>';
  $("#divstocklist").html(table);
  $("#divmessage").html(message);
  var d = new Date();
  $("#info").html("last update :   "+ d.getHours() + ":"+ d.getMinutes()+":"+ d.getSeconds());
  
  if(message!="")
  {
  	window.focus(); 
    newMessageRemind.show();
  }
	$('.editable').editable(function(value, settings) { 
	    var t1 = $(this).attr('ref');
	    var t2 = t1.split('-')
	    var i = t2[0];
	    var j = t2[1];
	    j = parseInt(j,10);
	    var ptype ;
	    
	    var ckey = sdata[i][1]+''+j;
	    var symbol = sdata[i][1];
	    var si;
	    switch(j)
	    {
	    case 4:
	    	ptype = 'buy_price';
	    	si = parseInt(sdata[i][5],10);
	   		if(si>0)
	   		{
	   			if(si<parseInt(value,10))
	   			{
	   				alert('下限价格应该小于上限价格');
	   				return sdata[i][6];
	   			}
	   		}
   			break;
	    case 5:
	    	ptype = 'alarm_max_price';
	    	si = parseInt(sdata[i][6],10);
	   		if(si>0)
	   		{
	   			if(si>parseInt(value,10))
	   			{
	   				alert('上限价格应该大于下限价格');
	   				return sdata[i][6];
	   			}
	   		}
	   		break;
	    case 6:
	    	ptype = 'alarm_min_price';
	    	si = parseInt(sdata[i][5],10);
	   		if(si>0)
	   		{
	   			if(si<parseInt(value,10))
	   			{
	   				alert('下限价格应该小于上限价格');
	   				return sdata[i][6];
	   			}
	   		}	  
	   		break;
	    }
	    if(!isNaN(value))
	    {
	    	db.set_alarm_price(symbol,ptype,value);
	    }
	     return(value);
	  }, { 
	     type    : 'text',
	     submit  : 'OK',
	     height    : 22,
	     width     : 50,
	     tooltip   :'',
	 });    
}

var newMessageRemind={   
	_step: 0,   
	_title: document.title,   
	_timer: null,   
	//显示新消息提示   
	show:function(){   
		var temps = newMessageRemind._title.replace("【　　　】", "").replace("【新消息】", "");   
		newMessageRemind._timer = setTimeout(function() {   
			newMessageRemind.show();   
			//这里写Cookie操作   
			newMessageRemind._step++;   
			if (newMessageRemind._step == 3) { newMessageRemind._step = 1 };   
			if (newMessageRemind._step == 1) { document.title = "【　　　】" + temps };   
			if (newMessageRemind._step == 2) { document.title = "【新消息】" + temps };   
		}, 800);   
		
		return [newMessageRemind._timer, newMessageRemind._title];   
	},   
	//取消新消息提示   
	clear: function(){   
		clearTimeout(newMessageRemind._timer );   
		document.title = newMessageRemind._title;   
		//这里写Cookie操作   
	}   
  
};  

/*
 * 
 function delete_symbol(symbol)
 {
 	var symbols = localStorage.getItem('symbols');	
 	if(symbols==null || symbols=='') return true;
 	var arr_symbols = symbols.split(",");
 	var ret = Array();
 	var s;
 	for(i=0;i<arr_symbols.length;i++)
 	{
 		s = arr_symbols[i];
 		if(symbol.length == 8 && s!=symbol)
 		{
 			ret.push(s);
 		}
 	}
 	localStorage.setItem('symbols',ret.join());	
 	return true;
 }
 function filter_symbols(symbols)
 {
 	if(symbols==null) return '';
 	var params = symbols.split(",");
 	var ret = Array();
 	var symbol ;
 	for(i=0;i<params.length;i++)
 	{
 		symbol = params[i];
 		if(symbol.length == 8)
 		{
 			ret.push(symbol);
 		}
 	}
 	return ret.join();
 }
 
 
 */
</script>
</head>
<body>
<div ><span id="info"></span> <span></span></div>
<div id="divstocklist"></div>

<div style="margin: 1px;">
<table>
	<tr>
		<td><input type="button" value=" 删 除 " id="btndel" /></td>
		<td><input type="button" value=" 开 始 " id="btnstart" /></td>
		<td><input type="button" value=" 停 止 " id="btnstop" /></td>
		<td><input type="button" value=" 清 除 " id="btnclear" /></td>
		<td>&nbsp;&nbsp;&nbsp;</td>
		<td><input type="button" value=" 保存数据到服务器  " id="btnsave" /></td>
		<td><input type="button" value=" 从服务器加载数据 " id="btnload" /></td>
		
	</tr>
</table>
</div>

<div style="margin-top: 10px;">

<table cellspacing="0" cellpadding="0" border="0">
	<tbody>
		<tr>
			<td><input type="text" value="600000" size="20" name="as_q"
				id="addcode" style="width: 150px;" required="required"></td>
			<td><input type="submit" value=" 添 加 " id="btnadd"></td>
		</tr>
	</tbody>
</table>
</div>

<div id="divmessage" style="left:50%;background-color:#FFFFAF"></div>
</body>
</html>